package com.zzw.zim.config;


import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.SwaggerUiConfigParameters;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>项目名称: zzw-tech </p>
 * <p>包名称: com.zzw.mis.config </p>
 * <p>描述: SpringDoc 配置 </p>
 * <p> SpringDoc 配置 </p>
 * <p>创建时间: 2022/11/15 14 </p>
 *
 * @author coco
 * @version v1.0
 */
@Configuration
public class SpringDocConfig {

	@Value("${prefix}")
	private String prefix;

	@Bean
	@Lazy(false)
	public List<GroupedOpenApi> apis (SwaggerUiConfigParameters swaggerUiConfigParameters, RouteDefinitionLocator locator) {
		List<GroupedOpenApi> groups = new ArrayList<>();
		List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList().block();
		assert definitions != null;
		definitions.stream().filter(routeDefinition -> !"openapi".equals(routeDefinition.getId())).forEach(routeDefinition -> {
			if (routeDefinition.getId().startsWith("ReactiveCompositeDiscoveryClient")) {
				return;
			}
			String name = routeDefinition.getPredicates().get(0).getArgs().values().stream().findFirst().get();
			if (name.contains("/admin/")) {
				return;
			}
			name = name.replace("/**", "").replace(prefix, "").replace("/", "");
			swaggerUiConfigParameters.addGroup(name);
			GroupedOpenApi.builder().pathsToMatch("/" + name + "/**").group(routeDefinition.getId()).build();
		});
		return groups;
	}


	@Bean
	public OpenAPI customOpenAPI () {
		Contact contact = new Contact();
		contact.setName("致筑网");

		return new OpenAPI().info(new Info().title("MIS监测平台").description("MIS监测平台").contact(contact).version("2.0").termsOfService("http://mis.zhizhuwang.online").license(new License().name("MIT").url("http://mis.zhizhuwang.online")));
	}
}
